<!-- eslint-disable no-unsafe-optional-chaining -->
<!-- eslint-disable no-unsafe-optional-chaining -->
<template>
  <div class="kg-header-search">
    <el-radio-group
      v-model="sysType"
      @change="changeType"
      :size="isArchives ? 'small' : ''"
    >
      <el-radio-button label="1">知识</el-radio-button>
      <el-radio-button label="2">事件</el-radio-button>
    </el-radio-group>
    <div class="search">
      <el-input
        v-model="name"
        placeholder="请输入"
        class="input-with-select"
        @focus="dialogVisible = false"
        :style="{
          width: isArchives ? '339px' : '880px',
          height: isArchives ? '32px' : '44px',
        }"
      >
        <template #prepend>
          <el-select
            v-model="entityType"
            placeholder="请选择"
            :style="{ width: isArchives ? '80px' : '125px' }"
          >
            <el-option
              v-for="item in selectList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
        <template #append>
          <div ref="buttonRef" class="icon icon-setting" @click="handleSetting">
            <i
              class="iconfont icon_system_fill"
              :class="entityType ? 'active' : ''"
            ></i>
          </div>
          <div class="icon icon-delete" @click="handleClear">
            <i
              class="iconfont icon_input_delete"
              :class="name ? 'active' : ''"
            ></i>
          </div>
          <el-button @click="handleSearch" :icon="Search" />
        </template>
      </el-input>
    </div>

    <el-popover
      popper-class="attrDialog"
      :visible="dialogVisible"
      title="高级搜索"
      trigger="click"
      :width="isArchives ? '400px' : '30%'"
      ref="popoverRef"
      :virtual-ref="buttonRef"
      virtual-triggering
    >
      <el-form ref="formRef" :model="dynamicValidateForm">
        <div
          v-for="(attr, index) in dynamicValidateForm.entityAttrList"
          :key="index"
          style="display: flex"
        >
          <el-col :span="6">
            <el-form-item
              :prop="'entityAttrList.' + index + '.code'"
              :rules="{
                required: true,
                message: '属性不能为空',
                trigger: 'change',
              }"
            >
              <el-select v-model="attr.code">
                <el-option
                  v-for="item in disableAttrList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-form-item
              :prop="'entityAttrList.' + index + '.value'"
              :rules="{
                required: true,
                message: '属性不能为空',
                trigger: 'blur',
              }"
            >
              <el-input v-model="attr.value"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="1">
            <el-form-item>
              <i
                class="iconfont icon_delete_fill"
                @click="handleDelAttr(index)"
              ></i>
            </el-form-item>
          </el-col>
        </div>
        <i
          class="iconfont icon_input_add1"
          :class="disableAdd ? 'disable' : ''"
          @click="handleAddAttr"
        ></i>
      </el-form>
      <div class="dialog-footer flex justify-end">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">
          确认
        </el-button>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "search-comp",
});

const props = defineProps({
  isArchives: Boolean,
  entityObj: Object,
});
const emit = defineEmits(["handleSearch"]);

import {
  entityTypeListApi,
  entityTypePropApi,
} from "@/api/kgKnowledgePortal/index";
import { useRouter } from "vue-router";

const router = useRouter();
const sysType = ref("1");
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
const name = ref("");
const entityType = ref("");
const entityList = ref([]);
const eventList = ref([]);
onMounted(async () => {
  await getEntityList("1");
  await getEntityList("2");
  //回显
  if (props.entityObj) {
    entityType.value = props.entityObj.entityType;
    name.value = props.entityObj.name;
    sysType.value = props.entityObj.comEntityAttr.sysType;
    entityAttrList.value = props.entityObj.entityAttrList;
  }
});
const selectList = computed(() => {
  return sysType.value === "1" ? entityList.value : eventList.value;
});
const getEntityList = async (type) => {
  let { code, data } = await entityTypeListApi({
    type: type,
    current: 1,
    size: 9999,
  });
  if (code === 200) {
    type === "1"
      ? (entityList.value = [{ code: "", name: "全部" }, ...data.records])
      : (eventList.value = [{ code: "", name: "全部" }, ...data.records]);
  }
};
const changeType = () => {
  entityType.value = "";
  entityAttrList.value = [];
  name.value = "";
  dialogVisible.value = false;
  if (props.isArchives) {
    let query = {
      entityType: entityType.value,
      name: name.value,
      comEntityAttr: sysType.value,
      entityAttrList: JSON.stringify(entityAttrList.value),
    };
    emit("handleSearch", query);
  }
};

const handleClear = () => {
  dialogVisible.value = false;
  if (!name.value) return;
  name.value = "";
};
/**
 * 高级搜索模块
 * */
import type { FormInstance } from "element-plus";
const dialogVisible = ref(false);
const attrList = ref([]);
const entityAttrList = ref([]);
const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive({
  entityAttrList: entityAttrList,
});

const buttonRef = ref();
const popoverRef = ref();
const disableAdd = computed(() => {
  return entityAttrList.value.length >= attrList.value.length;
});
//每个属性只能选择一次
const disableAttrList = computed(() => {
  return attrList.value.map((attr) => {
    let disabled = handleDisable(attr);
    return {
      ...attr,
      disabled,
    };
  });
});
const handleDisable = (attr) => {
  let flag = entityAttrList.value.findIndex((item) => {
    return item.code === attr.code;
  });
  return flag !== -1 ? true : false;
};
//用来判断类型变化没，变化后才重新请求
let isEntityType = ref(false);
watch(entityType, () => {
  isEntityType.value = true;
  dialogVisible.value = false;
});
const handleSetting = async () => {
  if (dialogVisible.value) {
    dialogVisible.value = false;
    return;
  }
  if (!entityType.value) return;
  if (!isEntityType.value) {
    dialogVisible.value = true;
    return;
  }
  let { code, data, msg } = await entityTypePropApi({ code: entityType.value });
  if (code === 200) {
    attrList.value = data;
    dialogVisible.value = true;
    if (entityType.value !== props.entityObj.entityType) {
      entityAttrList.value = [{ code: "", value: "" }];
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    });
    isEntityType.value = false;
  } else {
    ElMessage.warning(msg);
  }
};
const handleAddAttr = () => {
  if (disableAdd.value) return;
  entityAttrList.value.push({ code: "", value: "" });
};
const handleDelAttr = (index) => {
  entityAttrList.value.splice(index, 1);
};
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      dialogVisible.value = false;
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
const handleSearch = () => {
  dialogVisible.value = false;
  //处理参数，处理成为想要的格式
  entityAttrList.value = entityAttrList.value.map((item) => {
    attrList.value.forEach((attr) => {
      if (item.code === attr.code) {
        if (
          attr.dataType === "int" ||
          attr.dataType === "float" ||
          attr.dataType === "double"
        ) {
          item.value = Number(item.value);
        } else if (attr.dataType === "bool") {
          item.value = !!item.value;
        }
        item.dataType = attr.dataType;
      }
    });
    return item;
  });
  let query = {
    entityType: entityType.value,
    name: name.value,
    comEntityAttr: sysType.value,
    entityAttrList: JSON.stringify(entityAttrList.value),
  };
  //判断是否是在知识门户界面
  if (!props.isArchives) {
    const newpage = router.resolve({
      path: "/kgArchives/index",
      query: query,
    });
    window.open(newpage.href, "_blank"); // 打开新的窗口(跳转路径，跳转类型)
  } else {
    emit("handleSearch", query);
  }
};
</script>

<style scoped lang="scss">
.kg-header-search {
  margin-top: 36px;

  ::v-deep .el-radio-group {
    .el-radio-button {
      margin: 0 5px;

      .el-radio-button__inner {
        border-left: 1px solid #dcdfe6;
        border-radius: 4px;
      }
    }

    .el-radio-button.is-active {
      .el-radio-button__inner {
        border-left: 1px solid #2c51d7;
      }
    }
  }

  .search {
    margin-top: 5px;

    ::v-deep .input-with-select {
      height: 44px;

      .el-input-group__prepend {
        background: #fff;
        border-radius: 20px 0 0 20px;

        .el-select {
          margin: 0 -10px;

          .el-input__wrapper {
            box-shadow: none !important;
          }

          //.el-input.is-focus .el-input__wrapper {
          //  box-shadow: none !important;
          //}
        }
      }

      .el-input-group__append {
        position: relative;
        width: 64px;
        color: #fff;
        background: linear-gradient(180deg, #f4d432 0%, #f48325 100%);
        border-radius: 0 100px 100px 0;

        .icon {
          position: absolute;
          cursor: pointer;

          .iconfont {
            color: #ccc;
            cursor: not-allowed;
          }

          .iconfont.active {
            color: #17519f;
            cursor: pointer;
          }
        }

        .icon-setting {
          left: -24px;
        }

        .icon-delete {
          left: -50px;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.el-popover.el-popper.attrDialog {
  width: 180px;

  .el-popover__title {
    color: #2b1dff;
  }

  .iconfont {
    margin: 0 3px;
    font-size: 20px;
    cursor: pointer;
  }

  .iconfont.disable {
    color: #ccc;
    cursor: not-allowed;
  }
}
</style>
